package com.ldgame.applet;


import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;

import com.ldgame.game.Game;


public class GameApplet extends Applet {
	private static final long serialVersionUID = -1694162914257400936L;
	private Canvas display_parent;
	
	private Game test;
	
	private void startGame() {
		try {
			Display.setParent(display_parent);
		} catch (LWJGLException e) {
			e.printStackTrace();
		}
		
		test = new Game();
		test.start();
	}
	
	public void init() {
		setLayout(new BorderLayout());
		try {
			display_parent = new Canvas() {
				private static final long serialVersionUID = -15241398439002539L;
				
				@Override
				public final void addNotify() {
					super.addNotify();
					startGame();
				}
				
				@Override
				public final void removeNotify() {
					test.setRunning(false);
					
					try {
						test.getGameThread().join();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					super.removeNotify();
				}
			};
			
			display_parent.setSize(getWidth(),getHeight());
			add(display_parent);
			
			display_parent.setFocusable(true);
			display_parent.requestFocus();
			display_parent.setIgnoreRepaint(true);
			
			setVisible(true);
		} catch (Exception e) {
			System.err.println(e);
			throw new RuntimeException("Unable to create display.");
		}
	}
	
	public void destroy() {
		remove(display_parent);
		super.destroy();
	}
}
